# cython: language_level=3
import json
import os

from dotenv import load_dotenv
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from app.db.redis.invitation import get_response_plan_from_redis
from app.db.sql.day_ahead_plan import save_dayahead_plan
from app.db.sql.invitation import save_invitations
from app.db.sql.vpp_plan import save_vpp_plan
from app.db.sql.vpp_price import save_vpp_price
from app.schemas.platform import (
    GetInvitationRequest,
    SendReponsePlanRequest,
    GetDayaheadPlanRequest,
)
from common.database import get_db
from common.http import error_response, ok_response
from common.time import get_datetime_now

#ywy
# import app.webapp.show_getInvitation as show
# 
# 将一组接口（多i个接口）归为这个大标签下
router = APIRouter(tags=["platform-invitation"])
router.prefix = "/v2"
load_dotenv()
CREDIT_CODE = os.getenv("CREDIT_CODE")
INVITATION = os.getenv("INVITATION", "false") == "true"
BASE_DIR = os.getenv("BASE_DIR")



@router.post("/getInvitation")
def get_invitation(payload: GetInvitationRequest, db: Session = Depends(get_db)):
    """
    2.4
    由虚拟电厂平台调用负荷聚合平台接口，下发需求响应邀约,涉及到多页分发，则为多页的并集
    """
    if payload.creditCode != CREDIT_CODE:
        return error_response(5000, "creditCode不正确")
    # 如果creditcode正确，就将主站的邀约信息保存，不是统一保存，是分开保存
    save_invitations(db, payload)
        # ywy
    # show.save_invitation_payload(payload)
    return ok_response(None)


def read_json_file(filename):
    # check exist
    if not os.path.exists(filename):
        return {}
    with open(filename, 'r',encoding='utf-8') as f:
        f_data = f.read()
        data = json.loads(f_data)
    return data


@router.post("/sendResponsePlan")
def send_response_plan(payload: SendReponsePlanRequest, db: Session = Depends(get_db)):
    # 得把这里改了，因为这里浩哥是写死的，我要改成从网页上拿到传来的数据，存进数据库中，当主站启用这个接口时，我根据主码，从数据库中找到相应的信息，返回给主站
    """
    2.5
    虚拟电厂平台定时轮询负荷聚合平台接口，拉取用户计划曲线和价格；2.4接口中的邀约截止时间前定时调用此接口，直至邀约时间为止；
    """
    if payload.creditCode != CREDIT_CODE:
        return error_response(5000, "creditCode不正确")
    if INVITATION:
        # 接收邀约
        ret_data = {
            "creditCode": CREDIT_CODE,
            "invitationId": payload.invitationId,
            "replyTime": get_datetime_now(),
            "page": 1,
            "totalPage": 1,
            "replyResult": 1,
            "vppPrices": read_json_file("./json/price.json"),
            "vppPlans": read_json_file("./json/plan.json"),
            "responsePlan": get_response_plan_from_redis(),
        }
        # 不接收邀约
    else:
        ret_data = {
            "creditCode": CREDIT_CODE,
            "invitationId": payload.invitationId,
            "replyTime": get_datetime_now(),
            "page": 1,
            "totalPage": 1,
            "replyResult": 0,
            "vppPrices": {},
            "vppPlans": {},
            "responsePlan": [],
        }
    return ok_response(ret_data)


@router.post("/getDayaheadPlan")
def get_dayahead_plan(payload: GetDayaheadPlanRequest, db: Session = Depends(get_db)):
    """
    2.6
    虚拟电厂平台下发给用户出清后次日需求响应曲线，负荷聚合平台反馈是否接受成功。

    当出清计算完毕后，虚拟电厂平台主动调用负荷聚合平台的接口，将次日需求响应曲线发至负荷聚合平台，负荷聚合平台反馈是否接受成功,如果该计划分多页下发，则计划为多页计划的并集；
    """
    if payload.creditCode != CREDIT_CODE:
        return error_response(5000, "creditCode不正确")
    save_dayahead_plan(db, payload)
    save_vpp_plan(db, payload.invitationId, payload)
    save_vpp_price(db, payload.invitationId, payload)
    return ok_response(None)
